package com.cmas.platform.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


import com.aidex.common.annotation.DataSource;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.enums.DataSourceType;
import com.aidex.common.utils.PageUtils;
import com.aidex.common.utils.SecurityUtils;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmas.platform.config.NettyConfig;
import com.cmas.platform.domain.Message;

import com.cmas.platform.dto.MessageDto;
import com.cmas.platform.utils.PushNoticeUtils;
import com.cmas.platform.vo.LastMessageVo;
import com.cmas.platform.vo.MessageVo;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.platform.mapper.MessageMapper;
import com.cmas.platform.service.MessageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 消息表Service业务层处理
 *
 * @author su
 * @email 1218819874@qq.com
 * @date 2023-04-28
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);


    @Override
    public List<Message> selectMessageList(Message message) {
        QueryWrapper<Message> queryWrapper = setQueryWrapper(message);
        return baseMapper.selectList(queryWrapper);
    }


    /**
     * 查询消息表列表
     *
     * @param message 消息表
     * @return 消息表
     */
    @Override
    public List<MessageVo> selectMessageVoList(Message message) {
        QueryWrapper<Message> queryWrapper = setQueryWrapper(message);
        return baseMapper.selectMessageList(queryWrapper);
    }

    @Override
    public List<Message> selectLastMessageList(Message message) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(message.getToId())) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            queryWrapper = setRecordQueryWrapper(message, loginUser.getUserId());
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 批量删除消息表
     *
     * @param ids 需要删除的消息表ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteMessageByIds(String[] ids) {
        return baseMapper.deleteMessageByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public Message sendMessageByToId(Message message) {
        if (StringUtils.isNotEmpty(message.getToId())) {
            baseMapper.insert(message);
            PushNoticeUtils.sendChatMsg(message);
        }
        return message;
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<MessageDto> selectuserMessageList(List<SysUser> userList) {
        List<MessageDto> messageDtoList = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!userList.isEmpty()) {
            List<Message> messageList = baseMapper.selectUserMessage(loginUser.getUserId());
            MessageDto messageDto;
            if (!messageList.isEmpty()) {
                for (SysUser user : userList) {
                    if (!loginUser.getUserId().equals(user.getId())) {
                        messageDto = new MessageDto(user, new Message());
                        for (Message message : messageList) {
                            if (user.getId().equals(message.getToId()) || user.getId().equals(message.getFromId())) {
                                messageDto.setMessage(message);
                            }
                        }
                        messageDtoList.add(messageDto);
                    }
                }
            } else {
                for (SysUser user : userList) {
                    //排除自身
                    if (!loginUser.getUserId().equals(user.getId())) {
                        messageDto = new MessageDto(user, new Message());
                        messageDtoList.add(messageDto);
                    }
                }
            }
        }
        return messageDtoList;
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public IPage<LastMessageVo> selectLastMessageVoList(Integer current, Integer size, Message message) {
        Page<LastMessageVo> page = new Page<>(current, size);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        page.setRecords(baseMapper.selectLastMessage(current, size, loginUser.getUserId()));
        return page;
    }

    @Override
    public IPage<MessageVo> userMessageRecord(Integer current, Integer size, Message message) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Page<MessageVo> page = new Page<>(current, size);
        if (StringUtils.isNotEmpty(message.getToId())) {
            QueryWrapper<Message> queryWrapper = setRecordQueryWrapper(message, loginUser.getUserId());
            int total = baseMapper.selectCount(queryWrapper);
            int surplusSize = total % size;
            int pageSize = size;
            int currentPage = (total + size - 1) / size;
            if (surplusSize != 0 && surplusSize < size) {
                pageSize = size + surplusSize;
                currentPage-=1;
            }
            int pageCurrent = 0;
            page.setCurrent(currentPage);
            page.setTotal(total);
            if (currentPage > 1) {
                pageCurrent = (currentPage - 1) * size;
            }
            queryWrapper.last("limit " + pageCurrent + "," + pageSize);
            page.setRecords(baseMapper.selectMessageList(queryWrapper));
        }
        return page;
    }

    @Override
    public List<MessageVo> userMessageRecord(Message message) {
        PageUtils.startPage();
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(message.getToId())) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            queryWrapper = setRecordQueryWrapper(message, loginUser.getUserId());
        }
        return baseMapper.selectMessageList(queryWrapper);
    }

    public QueryWrapper<Message> setRecordQueryWrapper(Message message, String userId) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Message::getFromId, message.getToId())
                .eq(Message::getToId, userId)
                .or().eq(Message::getFromId, userId)
                .eq(Message::getToId, message.getToId())
                .orderByAsc(Message::getCreateTime);
        return queryWrapper;
    }

    public QueryWrapper<Message> setQueryWrapper(Message message) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(message.getFromId())) {
            queryWrapper.lambda().eq(Message::getFromId, message.getFromId());
        }
        if (StringUtils.isNotEmpty(message.getToId())) {
            queryWrapper.lambda().eq(Message::getToId, message.getToId());
        }
        if (StringUtils.isNotEmpty(message.getContent())) {
            queryWrapper.lambda().like(Message::getContent, message.getContent());
        }
        if (StringUtils.isNotEmpty(message.getType())) {
            queryWrapper.lambda().eq(Message::getType, message.getType());
        }
        return queryWrapper;
    }

}
